﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace WpfCsvDemo
{
    public partial class MainWindow : Window
    {
        private DataTable csvData = new DataTable();

        public MainWindow()
        {
            InitializeComponent();
            InitializeDataGrid();
        }

        // 初始化数据网格
        private void InitializeDataGrid()
        {
            // 设置DataGrid绑定
            dataGrid.ItemsSource = csvData.DefaultView;
            UpdateStatus("就绪 - 请加载CSV文件");
        }

        // 浏览文件按钮点击事件
        private void btnBrowse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "CSV文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
                Title = "选择CSV文件"
            };

            if (openFileDialog.ShowDialog() == true)
            {
                txtFilePath.Text = openFileDialog.FileName;
                UpdateStatus($"已选择文件: {Path.GetFileName(openFileDialog.FileName)}");
            }
        }

        // 加载文件按钮点击事件
        private void btnLoad_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFilePath.Text))
            {
                MessageBox.Show("请先选择CSV文件", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (!File.Exists(txtFilePath.Text))
            {
                MessageBox.Show("文件不存在，请重新选择", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            try
            {
                // 使用CSV帮助类读取文件
                csvData = CsvHelper.ReadCsv(txtFilePath.Text);
                dataGrid.ItemsSource = csvData.DefaultView;

                UpdateStatus($"成功加载: {Path.GetFileName(txtFilePath.Text)} - {csvData.Rows.Count} 行, {csvData.Columns.Count} 列");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                UpdateStatus($"加载失败: {ex.Message}");
            }
        }

        // 保存文件按钮点击事件
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFilePath.Text))
            {
                MessageBox.Show("请先选择文件路径", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            if (csvData.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可保存", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            try
            {
                // 使用CSV帮助类保存文件
                CsvHelper.SaveCsv(csvData, txtFilePath.Text);
                UpdateStatus($"文件保存成功: {Path.GetFileName(txtFilePath.Text)}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                UpdateStatus($"保存失败: {ex.Message}");
            }
        }

        // 导出为CSV按钮点击事件
        private void btnExport_Click(object sender, RoutedEventArgs e)
        {
            if (csvData.Rows.Count == 0)
            {
                MessageBox.Show("没有数据可导出", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                Filter = "CSV文件 (*.csv)|*.csv|所有文件 (*.*)|*.*",
                Title = "导出CSV文件",
                FileName = "exported_data.csv"
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                try
                {
                    // 使用CSV帮助类保存文件
                    CsvHelper.SaveCsv(csvData, saveFileDialog.FileName);
                    txtFilePath.Text = saveFileDialog.FileName;
                    UpdateStatus($"导出成功: {Path.GetFileName(saveFileDialog.FileName)}");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出文件时出错: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    UpdateStatus($"导出失败: {ex.Message}");
                }
            }
        }

        // 添加新行按钮点击事件
        private void btnAddRow_Click(object sender, RoutedEventArgs e)
        {
            if (csvData.Columns.Count == 0)
            {
                MessageBox.Show("请先加载CSV文件或添加列", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                return;
            }

            csvData.Rows.Add(csvData.NewRow());
            UpdateStatus($"添加了新行 - 当前行数: {csvData.Rows.Count}");
        }

        // 清空数据按钮点击事件
        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            if (csvData.Rows.Count > 0)
            {
                var result = MessageBox.Show("确定要清空所有数据吗？", "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    csvData.Clear();
                    UpdateStatus("数据已清空");
                }
            }
        }

        // 更新状态栏信息
        private void UpdateStatus(string message)
        {
            txtStatus.Text = message;
        }
    }
}